#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <zconf.h>
#include "sysinfo.h"
#include "getsysinfo.h"

//
// Created by ZhangKewei on 2019/12/24.
//
double cpu_rate() {
    struct cpu_stat cpu_stat1, cpu_stat2;
    getstat(&cpu_stat1);
//    printf("%llu %llu %llu %llu %llu %llu %llu\n", cpu_stat1.cpu_use,
//           cpu_stat1.cpu_nic, cpu_stat1.cpu_sys, cpu_stat1.cpu_idl, cpu_stat1.cpu_iow, cpu_stat1.cpu_irq,
//           cpu_stat1.cpu_softirq);
    sleep(1);
    getstat(&cpu_stat2);
//    printf("%llu %llu %llu %llu %llu %llu %llu\n", cpu_stat2.cpu_use,
//           cpu_stat2.cpu_nic, cpu_stat2.cpu_sys, cpu_stat2.cpu_idl, cpu_stat2.cpu_iow, cpu_stat2.cpu_irq,
//           cpu_stat2.cpu_softirq);


    struct cpu_stat cpu_statT2_T1 = {
            .cpu_use = cpu_stat2.cpu_use - cpu_stat1.cpu_use,
            .cpu_nic = cpu_stat2.cpu_nic - cpu_stat1.cpu_nic,
            .cpu_sys = cpu_stat2.cpu_sys - cpu_stat1.cpu_sys,
            .cpu_idl = cpu_stat2.cpu_idl - cpu_stat1.cpu_idl,
            .cpu_iow = cpu_stat2.cpu_iow - cpu_stat1.cpu_iow,
            .cpu_irq = cpu_stat2.cpu_irq - cpu_stat1.cpu_irq,
            .cpu_softirq = cpu_stat2.cpu_softirq - cpu_stat1.cpu_softirq,
    };

//    printf("%llu %llu %llu %llu %llu %llu %llu\n", cpu_statT2_T1.cpu_use,
//           cpu_statT2_T1.cpu_nic, cpu_statT2_T1.cpu_sys, cpu_statT2_T1.cpu_idl,
//           cpu_statT2_T1.cpu_iow, cpu_statT2_T1.cpu_irq, cpu_statT2_T1.cpu_softirq);

    //100% - idle/(user + system + iowait + idle)*100%
    double cpu_usage_rate = 1 - (double) cpu_statT2_T1.cpu_idl /
                                (double) (cpu_statT2_T1.cpu_use +
                                cpu_statT2_T1.cpu_sys +
                                cpu_statT2_T1.cpu_iow +
                                cpu_statT2_T1.cpu_idl);
//    printf("%.2lf\n", cpu_usage_rate * 100);
    return cpu_usage_rate * 100;
}
